﻿#include "tmlogger.h"

TmLogger::TmLogger(QString strExeRoot,QObject *parent) : QObject(parent)
{
    m_ProPath = strExeRoot;

    QDateTime time = QDateTime::currentDateTime();
    m_FileName = QString("%1/Logger/%2.txt").arg(m_ProPath).arg(time.toString("yyyy_MM_dd_hh"));
    m_file.setFileName(m_FileName);

    if(m_file.open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text))
    {
        m_file.write("CTmLogger::Init() \t\n");
        m_file.flush();
        //start thread
    }

    QString path = QString("%1/Logger").arg(m_ProPath);
    QDir dir(path);
    //dir.entryInfoList(QDir::Files)返回文件信息
    foreach(QFileInfo fileInfo, dir.entryInfoList(QDir::Files))
    {
        QString name = fileInfo.baseName();
        QStringList nameList = name.split("_");
        if(nameList.length() >= 3)
        {
            QString time = nameList[0]+nameList[1]+nameList[2];
            if(Get_day_num(time) > 7)
                fileInfo.dir().remove(fileInfo.fileName());
        }

    }

}

void TmLogger::slot_LoggerStrAppend(QString data)
{
    //qDebug()<<"TmLogger::slot_LoggerStrAppend"<<QThread::currentThreadId();

    QDateTime time = QDateTime::currentDateTime();
    QString TimeData = QString("%1/Logger/%2.txt").arg(m_ProPath).arg(time.toString("yyyy_MM_dd_hh"));
    if(m_FileName != TimeData)
    {
        m_file.close();
        m_file.setFileName(TimeData);

        if(m_file.open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text))
        {
            m_file.write("CTmLogger::Init() \t \n");
            m_file.flush();
            m_FileName = TimeData;
            //start thread
        }
    }

    m_LogStr.append(data);
    slot_SaveLog();
}


void TmLogger::slot_SaveLog()
{
    for(int i = m_LogStr.length() - 1; i>=0 ; i--)
    {
        QDateTime time = QDateTime::currentDateTime();
        QString strTimer = time.toString("hh:mm:ss.zzz");
        QString m_szLog = QString("TransRobot [%1]:      %2 \t\n")
                .arg(strTimer)
                .arg(QString(m_LogStr[i]));
        m_file.write(m_szLog.toUtf8().data());
        m_file.flush();
        m_LogStr.removeAt(i);
    }
}

int TmLogger::Get_day_num(QString data1)
{
    QDateTime time;
    time = QDateTime::fromString(data1, "yyyyMMdd");

    QDateTime time2;
    time2 = QDateTime::currentDateTime();
    int days = time.daysTo(time2);

    return days;

}
